package com.example.experiment3.service;

import org.apache.commons.csv.CSVFormat;
import org.apache.commons.csv.CSVRecord;
import org.assertj.core.util.Lists;
import org.springframework.core.io.Resource;
import org.springframework.http.RequestEntity;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.util.UriComponents;
import org.springframework.web.util.UriComponentsBuilder;
import java.io.*;
import java.net.URI;
import java.util.List;


@Service
public class MyService {


    public  static Resource fetchData() {
        String uriTemplate = "https://gitee.com/dgut-sai/COVID-19/raw/master/csse_covid_19_data/csse_covid_19_time_series/time_series_covid19_confirmed_global.csv";
        UriComponents uriComponents = UriComponentsBuilder
                .fromUriString(uriTemplate)
                .encode()
                .build();
        URI uri = uriComponents.toUri();

        RequestEntity<Void> requestEntity = RequestEntity
                .get(uri)
                .headers(httpHeaders -> httpHeaders.add("User-Agent", "Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/65.0.3325.181 Safari/537.36"))
                .build();

        ResponseEntity<Resource> exchange = new RestTemplate().exchange(requestEntity, Resource.class);
        Resource body = exchange.getBody();
        return body;
    }

    public static List<CSVRecord> CsvToCsvrecord() {
        Resource resource = fetchData();
        try {
            InputStream in = resource.getInputStream();
            BufferedReader reader = new BufferedReader(new InputStreamReader(in));
            List<CSVRecord> records = Lists.newArrayList( CSVFormat.RFC4180.withFirstRecordAsHeader().parse(reader));
            return records;
        } catch (IOException exception) {
            System.out.println("异常:" + exception);
            return null;
        }
    }

//    public String latitudeQuery(){
//        String local="china";
//        String uriTemplate="http://api.map.baidu.com/geocoder/v2/";
//        UriComponents uriComponents = UriComponentsBuilder
//                .fromUriString(uriTemplate)
//                .queryParam("address",local)
//                .queryParam("output","json")
//                .queryParam("ak","GrfpdE3WyT8ZY6oOnb26pCxPEBLxGkuO")
//                .queryParam("callback","showLocation")
//                .encode()
//                .build();
//        URI uri = uriComponents.toUri();
//        RequestEntity<Void> requestEntity = RequestEntity
//                .get(uri)
//                .build();
//        ResponseEntity<Resource> exchange=new RestTemplate().exchange(requestEntity,Resource.class);
//        Resource body = exchange.getBody();
//        return null;
//}


}
